// 引入接口文件
import {
  queryAgent,
  create,
  edit,
  queryInfo,
  queryRuleInfo,
  importAccount,
  submit,
  delFile,
  projectFilter,
  queryProductList,
  selectProject,
  verifyCommissionTokenFun
} from './levelCommissionsRulesEditServ'

// 对象和JSON字符串互转
// import { parse } from 'qs'
// 弹出消息框
import { Modal,message } from 'antd'
const confirm = Modal.confirm;
// 日期处理对象
// import moment from 'moment'
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import $ from 'jquery'
import { isEmpty, isArray, cloneDeep, merge, pick,set,get } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
// import AppBus from '../../../utils/bus'
import { download} from 'utils/util'
import config from 'config/config'
// import {reqInform, showConfirm} from 'utils/notification'
// import { array } from 'prop-types';
// 初始默认状态
const defultState = {
  id: '',
  keys: 0,
  url: '',
  loading: false,
  distCoId: '',
  submitType: '',
  btnLoading: false,
  projectFilterParams: [],
  actionType: 'detail', //查看
  selectedRowKeys: [],
  distributionNameList: [],
  createFaymentMethodFlag: true,
  biz:{},
  biz1: {},
  biz2: {},
  biz3: {},
  biz4: {},
  imageUrls: [],
  uploadFileObj: {//导入
    visible: false,
    loading: false,
  },
  fileList: [],
  formatsKey: '',
  detail:{
    name: '',
    projectname:'',
    projectId:'',
    regionName: '',
    computeNodes:'',
    startTime: '',
    endTime:'',
    remark: '',
    noCommission: 0,//特例规则状态
    noCommissionRemark: '',//特例规则说明
    // contractId:  '', //合同id
    // contractAnnex:  '',//合同url
    // enclosureId:  '',//附件ID
    // enclosureUrl:  '',//附件url
    // enclosureName:   '',//附件名称
    wxyxTowcomruleBList:[],
  },
  tableObj: {
    amount: 0,
    bpmStatus: "",
    createBy: "",
    createDate: "",
    createName: "",
    fkcdf: "",
    fytype: "",
    hid: "",
    id: "",
    productid: "",
    productname: "",
    proportion: 0,
    remark: "",
    sysCompanyCode: "",
    sysOrgCode: "",
  },
  // 表格数据
  tableData: {
    dataSource: [],
    total: 0,
    stop:0,
    start:0
  },
  // 表格分页设置
  pageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
  
  selectedKeys: [],
  selectedRows: [],
  
  projectModalObj: {
    visible: false,
  },
  formatsModalObj: {
    visible: false,
  },
  codeModalObj: {
    visible: false,
  },
  enclosureNameModalObj: {
    visible: false,
  },
  fileModalObj: {
    visible: false,
  },
  searchData: {
    productName: '',
  },
  productDataList:[],
  productListObj: {
    dataSource: [],
    total: 0,
    stop:0,
    start:0
  },
  productPageConfig: {
    pageSize: Number.parseInt(config.smallPageSizeList[0]),
    pageNo: 1
  },
  accountingModalObj:{
    visible: false,
    isTransferProperty:'',
    projectId:'',
    projectName:''
  },
}
// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          query.id=query.id+''
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          console.log('subscriptions', pathname, query)
          if (query.actionType == 'check' ||query.actionType == 'upVersion' ) {
            // dispatch({type: 'queryInfo',payload: {actionType: query.actionType,id: query.id, } })
          } else {
            dispatch({type: 'updateStore',payload: {actionType: query.actionType,id: query.id, } })
          }
          dispatch({type: 'projectFilter',payload: {actionType: query.actionType,id: query.id, } })
          dispatch({type: 'queryProductList',payload: {} })
        } // end if
      }) // end listen
    },
  },
  
  // 方法列表
  effects: {
    * queryProductList({payload}, {put, call, select}) {
      if(yield call(verifyCommissionTokenFun,{})){
        let {productListObj,productDataList,actionType} = yield select(state => state[tmpModule.namespace])
        let params = {
          pageSize:'10000',
          pageNo:'1',
        }
        let { success, msg, result } = yield call(queryProductList, {...params})
        if(success){
          productListObj.dataSource = result
          productDataList = result
          yield put({type: 'updateStore', payload: {productListObj,productDataList}})
          if(actionType == 'edit'||actionType == 'upVersion'||actionType == 'check'){
            yield put({type: 'queryInfo', payload: {}});
            yield put({type: 'queryRuleInfo', payload: {}});
          }
        }
      }
    },
    *queryAgent({payload},{put,select,call}){
      let {detail,distributionNameList} = yield select(state => state[tmpModule.namespace])
      if(!detail.projectId){
        message.warn('请先选择项目名称')
        return false
      }
      let params = {
        projectId: detail.projectId,
        tagType: 0
      }
      const { success, msg, data=[] } = yield call(queryAgent, {...params})
      if(success&&data.length){
        for(var i=0;i<data.length;i++){
          for(var j =data.length - 1; j > 0; j--){
            if(data[i].orgName ==  data[j].orgName && i != j){
              data.splice(j, 1);
            }
          }
        }
        distributionNameList = data
        yield put({
          type: 'updateStore',
          payload: {
            distributionNameList
          }
        })
      }
    },
    *create({payload},{put,select,call}){
      if(yield call(verifyCommissionTokenFun,{})){
        let {submitType,detail,tableData} = yield select(state => state[tmpModule.namespace])

        let params = detail
        let tempList = tableData.dataSource;
        let find = false;
        let required = false
        let arr = []
        params.wxyxTowcomruleBList = tableData.dataSource
        if(!params.id){
            console.log(params.id);
          //不包含ID为录入
          const { success, msg, data,code } = yield call(create, {...params})
          if(code){
            yield put({type: 'updateStore', payload: {uploading:false}})
          }
          if(success){
            message.success('保存成功')
            hashHistory.push({
              pathname: '/home/commissions/levelCommissionsRules',
              query: {}
            })
          }
        }else{
            console.log('编辑');
          //包含Id为编辑
          const { success, msg, data,code } = yield call(edit, {...params})
          if(code){
            yield put({type: 'updateStore', payload: {uploading:false}})
          }
          if(success){
            message.success('修改成功')
            hashHistory.push({
              pathname: '/home/commissions/levelCommissionsRules',
              query: {}
            })
          }
        }
      }
    },
    *queryInfo({payload}, {put, select, call}){
      if(yield call(verifyCommissionTokenFun,{})){
         //查询明细
         let {id,detail,tableData,productDataList} = yield select(state => state[tmpModule.namespace])
         let params = { "id":id }
         const {result, success, msg} = yield call(queryInfo, {...params});
         if(success){
           detail= result
           yield put({type: 'updateStore',payload: {detail}})
         }
         console.log(detail);
      }
    },
    *queryRuleInfo({payload}, {put, call, select}) {
      if(yield call(verifyCommissionTokenFun,{})){
        //查询明细
        let {id,detail,tableData,productDataList} = yield select(state => state[tmpModule.namespace])
        let params = { "id":id }
        const { result, success, msg} = yield call(queryRuleInfo, {...params});
        if(success){
          tableData.dataSource = result
          yield put({type: 'updateStore',payload: {tableData}})
        }
        console.log(tableData);
      }
    },
    * importAccount ({payload}, {put, call, select}) {
      if(yield call(verifyCommissionTokenFun,{})){
        let {detail,uploadFileObj, imageUrls} = yield select(state => state[tmpModule.namespace])
        let fileUrl = imageUrls[0] && imageUrls[0].url || ''
        let fileName = imageUrls[0] && imageUrls[0].name || ''
      
        if (!fileUrl) {
          message.error('请上传文件')
          return false
        }
        uploadFileObj.loading = true
        yield put({type: 'updateStore', payload: {uploadFileObj}})
        let params = {
          url: fileUrl,
          fileName: fileName,
          projectId: detail.projectId
        }
        const {data, success, msg} = yield call(importAccount, {...params})
        if (success === true) {
          message.success('操作成功')
        }
        uploadFileObj.visible = false
        uploadFileObj.loading = false
      }
    },

    *submit({payload},{put,select,call}){
      if(yield call(verifyCommissionTokenFun,{})){
        let params = {
          id: payload.id,
          tab: 1
        }
        const { success, msg, data } = yield call(submit, {...params})
        if(msg){
          yield put({type: 'updateStore', payload: {btnLoading: false,}})
        }
        if(success){
          message.success('提交成功')
          hashHistory.push({
            pathname: '/home/commissions/commissionsDistRules',
            query: {}
          })
        }
      }
    },
    *delFile({payload},{put,select,call}){
      if(yield call(verifyCommissionTokenFun,{})){
        let params = {
          id: payload.fileId,
        }
        const { success, msg, data } = yield call(delFile, {...params})
        if(success){
          message.success('删除成功')
        }
      }
    },
    *projectFilter({payload}, {put, call, select}) {
      if(yield call(verifyCommissionTokenFun,{})){
        let {projectFilterParams} = yield select(state => state[tmpModule.namespace])
      
        const {result, success} = yield call(projectFilter)
        if(success){
          projectFilterParams = result
          yield put({
            type: 'updateStore',
            payload: {
              projectFilterParams
            }
          })
        }
      }
    },
    *selectProject({payload}, {put, call, select}) {
      if(yield call(verifyCommissionTokenFun,{})){
        let {projectList,accountingModalObj} = yield select(state => state[tmpModule.namespace])
        let params = {
            projectName:accountingModalObj.projectName
        }
        const {success,result} = yield call(selectProject,params)
        if(success){
          projectList = result
          yield put({type: 'updateStore',payload: {projectList}})
        }
      }
    },
    
    * selectedKeysChange ({payload}, {put, select, call}) {
      let {selectedRowKeys,selectedRows} = yield select(state => state[tmpModule.namespace])
      selectedRowKeys=payload.selectedRowKeys
      selectedRows=payload.selectedRows
      yield put({
        type: 'updateStore',
        payload: {
          selectedRowKeys,selectedRows
        }
      })
    },
    * selectedKeysChange1 ({payload}, {put, select, call}) {
      let {tableData,formatsKey} = yield select(state => state[tmpModule.namespace])
      for(var item of tableData.dataSource){
        if(item.key == formatsKey){
          item.productSelectedKeys =payload.selectedRowKeys
          item.productSelectedRows =payload.selectedRows
        }
      }
      yield put({
        type: 'updateStore',
        payload: {
          tableData
        }
      })
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
